package com.controller.library;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.*;

import com.action.library.*;

import com.bean.library.AppraisedOption;
import com.bean.library.AppraisedPaper;
import com.bean.library.AppraisedSubject;
import com.bean.library.DbPaper;
import com.bean.library.DbSubject;
import com.bean.library.Option;
import com.bean.library.Paper;
import com.bean.library.Student;
import com.bean.library.Subject;
import com.bean.library.UserOption;
import com.bean.library.UserPaper;

public class SubmitServlet extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!统一方法，要么全部用post，要么全部用get
		Paper paper = (Paper)request.getSession().getAttribute("paper");
		String isSubmit = request.getParameter("is_submit");
		int curPageNum = Integer.parseInt(request.getParameter("page_num"));
		if(isSubmit.equals("yes")){
			if(request.getSession().getAttribute("appraisedPaper")!=null){
				request.getSession().removeAttribute("appraisedPaper");
				request.getSession().removeAttribute("partialAppraisedPaper");
				request.getSession().removeAttribute("userPaper");
			}
			//getApparisedPaper(request, subjectIndexBegin, pageCount)
			//System.out.println("最终提交");
			AppraisedPaper appraisedPaper = getApparisedPaper(request, (curPageNum-1)*10, 10);
			request.getSession().setAttribute("appraisedPaper", appraisedPaper);
			
			Student student = (Student) request.getSession().getAttribute("student");
			if(student!=null){
				AppraisePaperAction appraisedPaperAction = new AppraisePaperAction();
				appraisedPaperAction.saveStudentScore(student.getStudentId(),appraisedPaper.getPaperId(), appraisedPaper.getScore());
			}
			
			AppraisedPaper partialAppraisedPaper = new AppraisedPaper();
			partialAppraisedPaper.setScore(appraisedPaper.getScore());
			partialAppraisedPaper.setSubjectList(appraisedPaper.getSubjectList(0, 10));
			partialAppraisedPaper.setPaperName(appraisedPaper.getPaperName());
			request.getSession().setAttribute("partialAppraisedPaper", partialAppraisedPaper);
			try {
				response.sendRedirect("/Exam1/student/page/grade.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
			int pageNum = Integer.parseInt(request.getParameter("submit_page_num"));
			if(pageNum > curPageNum)
				savePage(request, (pageNum - 2)*10, 10);
			else
				savePage(request, pageNum*10, 10);
//			try{		
//				response.sendRedirect("/Exam1/student/page/grade.jsp");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			Paper partialPaper = new Paper();
			partialPaper.setPaperName(paper.getPaperName());
			partialPaper.setStartIndex(pageNum - 1);
			partialPaper.setSubjectList(paper.getSubjectList((pageNum-1)*10, 10));
			request.getSession().setAttribute("partialPaper", partialPaper);
			try{		
				response.sendRedirect("/Exam1/student/page/paper.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}	
	}
	
	//参数说明：subjectIndexBegin 为该页的开始题号，pageCount为一页显示的条数
	public void savePage(HttpServletRequest request,int subjectIndexBegin,int pageCount){
		//获得白卷
		Paper paper = (Paper)request.getSession().getAttribute("paper");
		if(paper==null){
			int paperId = (int)(request.getSession().getAttribute("paperId"));
			GeneratePaperAction generatePaperAction = new GeneratePaperAction();
			paper = generatePaperAction.generatePaper(paperId);
		}
		//获得用户的试卷（部分完成）
		UserPaper userPaper;
		if(request.getSession().getAttribute("userPaper") == null){
			userPaper = new UserPaper(paper);
			request.getSession().setAttribute("userPaper",userPaper);			
		}
		else{
			userPaper = (UserPaper)request.getSession().getAttribute("userPaper");
		}
		ArrayList<Subject> userSubjectList = userPaper.getSubjectList();
		int subjectCount = userSubjectList.size();
		for(int i = subjectIndexBegin;i<subjectCount&&i<subjectIndexBegin+pageCount;i++){
			Subject userSubject = userSubjectList.get(i);
			ArrayList<Option> userOptionList = userSubject.getOptList();
			int userOptionCount = userOptionList.size();
			for(int j = 0;j<userOptionCount;j++){
				UserOption userOption = (UserOption)userOptionList.get(j);
				if(userOption.isMulti()){
					//多选的覆盖会有一些bug，当值不为“on”的时候无法更改
					if(request.getParameter(userOption.getOptName()) != null){
						
						if(request.getParameter(userOption.getOptName()).equals("on")){
							
							userOption.setChecked(true);
						}
					}
					else {
						userOption.setChecked(false);
					}
				}
				else {
					if(request.getParameter(userOption.getOptName()) != null){
//						System.out.println("这个是单选"+userOption.getOptName()+"获得的value:"+request.getParameter(userOption.getOptName()));
//						System.out.println("这个是userOption.getOptId()"+userOption.getOptId());
						String tmp1 = request.getParameter(userOption.getOptName()); 
						String tmp2 = String.valueOf(userOption.getOptId());
						if(tmp1.equals(tmp2)){
							userOption.setChecked(true);
						}
					}
					else {
						userOption.setChecked(false);
					}
				}
			}
		}
		request.setAttribute("userPaper",userPaper);//刷新
		
	}
	public AppraisedPaper getApparisedPaper(HttpServletRequest request,int subjectIndexBegin,int pageCount){
		//首先保存本页信息
		
		savePage(request,subjectIndexBegin,pageCount);
		
		UserPaper userPaper = (UserPaper)request.getSession().getAttribute("userPaper");
		//System.out.println("userPaper总分："+userPaper.getPaperScore());
		/************试卷没有做完***************/
		if(userPaper==null){
			
		}
		if(!userPaper.isFinised()){
			
		}
		/*************试卷没有做完***************/
		
		AppraisePaperAction appraisedPaperAction= new AppraisePaperAction();
		AppraisedPaper appraisedPaper =  appraisedPaperAction.getAppraisedPaper(userPaper);
		//后台显示
		/*
		ArrayList<Subject> appraisedSubjectList = appraisedPaper.getSubjectList();
		int subCount = appraisedSubjectList.size();
		System.out.println("appraisedPaper总分："+appraisedPaper.getPaperScore());
		System.out.println("本套试卷得分："+appraisedPaper.getScore());
		for(int i = 0;i<subCount;i++){
			AppraisedSubject appraisedSubject = (AppraisedSubject)appraisedSubjectList.get(i);
			System.out.print(appraisedSubject.getSubjectContent()
					+"----"+appraisedSubject.getSubjectId());
			if(appraisedSubject.isRight()){
				System.out.println("----正确！");
			}
			else{
				System.out.println("----错误！");
			}
			ArrayList<Option> appraisedOptionList = appraisedSubject.getOptList();
			int optCount = appraisedOptionList.size();
			for(int j = 0;j<optCount;j++){
				AppraisedOption appraisedOption = (AppraisedOption)appraisedOptionList.get(j);
				System.out.print(""+j+":"
				+appraisedOption.getOptContent());
				if(appraisedOption.isChecked()){
					System.out.print("---O---");
				}
				if(appraisedOption.isRight()){
					System.out.print("---V---");
				}
				System.out.println("");
			}
		}
		*/
		//testInsert();
		//System.out.println("开始时间："+appraisedPaper.getStartTime()+"----结束时间："+appraisedPaper.getFinishDate()+"---历时："+appraisedPaper.getLastTimeMs()/1000);
		//System.out.println("当前时间："+appraisedPaper.getDateNow().toString());
//		System.out.println("获取试卷状态："+appraisedPaper.getTimeStat());
		return appraisedPaper;
	}
	/*private void testInsert(){
		DbPaper dbPaper = new DbPaper();
//		String paperName = request.getParameter("paper_name");
		String paperName = "测试试卷 试卷名";
		//long totalTime = (long)(60*60*1000*Float.valueOf(request.getParameter("total_time")));//以毫秒为单位
		long totalTime = (long)(60*60*1000*2.5);//以毫秒为单位
		//float totalScore = Float.valueOf(request.getParameter("total_score"));
		float totalScore = 120;
		//int courseId = Integer.valueOf(request.getParameter("course_id"));
		String courseId = "304031030";
		boolean isSparePaper = false;
//		if(request.getParameter("is_spare_paper")!=null&&request.getParameter("is_spare_paper").equals("on")){
//			isSparePaper = true;
//		}
		
//		String beginDateStr = request.getParameter("begin_date");
		String beginDateStr = "2012/12/21 8:00";
//		int teacherId = (int) request.getSession().getAttribute("teacherId");
		Date beginDate = new Date(beginDateStr);
		String teacherId = "000002";
		float passScore = 0.6f*totalScore;//及格分数没有在页面中给出，所以在这里设s为总分的0.6
		dbPaper.setCourseId(courseId);
		dbPaper.setLastTimeMs(totalTime);
		dbPaper.setNoEnterTime(null);//这个不整了
		dbPaper.setPaperName(paperName);
		dbPaper.setPaperScore(totalScore);
		dbPaper.setPassScore(passScore);
		dbPaper.setStartTime(beginDate);
		//dbPaper.setStartTime(startTime)//!时间的获取还是一个值得商榷的问题
		dbPaper.setStatus(!isSparePaper);//亲爱的昶老师，不知道您的status是不是这个意思
		System.out.println("isSparePaper "+isSparePaper);
		System.out.println(dbPaper.getStatus());
		dbPaper.setTeacherId(teacherId);
		ArrayList<Subject> submitSubjectList = new ArrayList<Subject>();
		for(int i = 1;i<10;i++){
//			String subjectContent = request.getParameter(i+"_"+"title");
//			String subjectSurface = request.getParameter(i+"_"+"surface");
			String subjectContent = "昶老师的的年龄？";
			String subjectSurface = "";
//			int subjectDifficulty = Integer.valueOf(request.getParameter(i+"_"+"difficulty"));
			int subjectDifficulty = 2;
//			if(subjectContent==null){
//				break;
//			}
			
			DbSubject submitSubject = new DbSubject();
			//Subject.isMulti不用写入
			submitSubject.setSubjectContent(subjectContent);
			submitSubject.setCourseId(courseId);
			submitSubject.setDifficulty(subjectDifficulty);
			submitSubject.setSurface(subjectSurface);
			ArrayList<Option> submitOptionList = new ArrayList<Option>();
			for(int j = 1;j<5;j++){
//				String optContent = request.getParameter(i+"_"+j+"_"+"content");
//				String optValue = request.getParameter(i+"_"+j);
				String optContent = "25岁";
				String optValue = "1";
				boolean optChecked;
				if(optValue.equals("1")){
					optChecked = true;
				}
				else {
					optChecked = false;
				}
//				if(optContent==null){
//					break; 
//				}
				UserOption submitOption = new UserOption();
				submitOption.setOptContent(optContent);
				submitOption.setChecked(optChecked);
				submitOptionList.add(submitOption);
			}
			submitSubject.setOptList(submitOptionList);
			submitSubjectList.add(submitSubject);
		}
		dbPaper.setSubjectList(submitSubjectList);
		System.out.println("开始保存试卷");
		SavePaperAction savePaperAction = new SavePaperAction();
		savePaperAction.savePaper(dbPaper);
		System.out.println("结束保存");
	}*/
}